package repositories

import (
	"huanteng/web/global/application"
	"huanteng/web/models"
)


type RoleMenuRepository struct {

}


func (a *RoleMenuRepository)SetRoleMenus(roleid uint, menuids []uint) error {

	//事物准备额
	tx := application.DB.Begin()
	//延迟恢复
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	//该角色关联的所有角色菜单数据
	if err := tx.Where(&models.RoleMenu{RoleID: roleid}).Delete(&models.RoleMenu{}).Error; err != nil {
		tx.Rollback()
		return err
	}


	//设置角色菜单关联
	if len(menuids) > 0 {
		for _, mid := range menuids {
			rm := new(models.RoleMenu)
			rm.RoleID = roleid
			rm.MenuID = mid
			if err := tx.Create(rm).Error; err != nil {
				tx.Rollback()
				return err
			}
		}
	}
	//如果是many to many orm添加关联可以如下
	//application.DB.Model(&models.Role{ID: roleid}).Association([]models.Menu{})
	return tx.Commit().Error


}
